package com.decent.exception;

import com.decent.entity.common.Message;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ValidationException;
import java.util.Objects;

/**
 * @Author: 吃瓜
 * @Description:
 * @Date Created in 2021-04-01 0:10
 * @Modified By:
 */
@ControllerAdvice
@Component
public class GlobalExceptionConfig {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Message throwCustomException(MethodArgumentNotValidException methodArgumentNotValidException) {
        String exceptionMessage = methodArgumentNotValidException.getMessage();
        Message message = new Message();
        message.setErrorMsg(Objects.requireNonNull(methodArgumentNotValidException.getBindingResult().getFieldError()).getDefaultMessage());
        message.setErrorCode(404);
        return message;

    }

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Message throwExcept(RuntimeException e) {
        String eMessage = e.getMessage();
        Message message = new Message();
        message.setErrorMsg(eMessage);
        message.setErrorCode(404);
        return message;
    }
}
